import {
  Card,
  Button,
  Divider,
  Space,
  Table,
  Tag,
  Modal,
  Form,
  Input,
  InputNumber,
  Pagination,
  message,
  Upload,
} from "antd";
import {
  LoadingOutlined,
  PlusOutlined,
  FormOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import type { UploadChangeParam } from "antd/es/upload";
import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";
import {deleteTrademark,addTrademark,editTrademark} from '@/api/trademark'
import {
  getTrademarkListSync,
  useSelectorTrademark,
} from "@/store/slices/trademark";
import { useAppDispatch } from "@/hooks";
import type { ColumnsType } from "antd/es/table";
import type { PaginationProps } from "antd";
// import React from 'react';
import React, { useState, useEffect } from "react";
import "./index.less";
interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}


let id = 0
let currentPage:number =1
let pageSize:number=5
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};

// 上传图片LOGO相关
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
};
// 上传图片LOGO相关
const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("You can only upload JPG/PNG file!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("Image must smaller than 2MB!");
  }
  return isJpgOrPng && isLt2M;
};

const normFile = (e: any) => {
  console.log("Upload event:", e);
  if (Array.isArray(e)) {
    return e;
  }
  return e && e.fileList;
};

const Index: React.FC = () => {
  const dispatch = useAppDispatch();
  //收集数据
  const [form] = Form.useForm();

  // const data: DataType[] = useSelectorTrademark()
  const { trademarkList } = useSelectorTrademark();
  const data = trademarkList.records;
  // console.log(data)
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const onReset = () => {
    form.resetFields();
  };
  const handleOk = (values: any) => {
    setIsModalOpen(false);
    // const res = onFinish(values);
    // console.log(res, 1111);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    setImageUrl(undefined)
    onReset()
  };
  const onFinish =async (value: any) => {
    console.log("onfinish", value);
    setIsModalOpen(false);
    setImageUrl(undefined)
    console.log(value.id,'qweqwe')
    if(id){
      const data={
        id:id||undefined,
        tmName:value.logoName,
        logoUrl:value.logoImg ? value.logoImg[0].response.data:imageUrl 
      }
      console.log(imageUrl)
      console.log(id)
      await editTrademark(data)
    }else{
      const data={
        // id:value.id||undefined,
        tmName:value.logoName,
        logoUrl:value.logoImg[0].response.data
      }
      console.log(id)
      await addTrademark(data)
    }
    await dispatch(getTrademarkListSync(currentPage, pageSize))
    onReset()
    id = 0
  };

  // 删除
  const columns: ColumnsType<DataType> = [
    {
      title: "序号",
      // dataIndex: 'id',
      // key: 'id',
      render: (text, record, index) => index + 1,
    },
    {
      title: "品牌",
      dataIndex: "tmName",
      // key: 'tmName',
    },
    {
      title: "品牌LOGO",
      dataIndex: "logoUrl",
      render: (recode) => <img src={recode} width="100px"></img>,
      // key: 'logoUrl',
    },
    {
      title: "操作",
      // key: 'action',
      render: (row) => {
        // 删除数据
        const deleteInfo = async()=>{
          await deleteTrademark(row.id)
          await dispatch(getTrademarkListSync(1, 5))
        }
        const editInfo = ()=>{
          setIsModalOpen(true);
          form.setFieldsValue({"logoName":row.tmName})
          setImageUrl(row.logoUrl)
          // form.setFieldsValue("logoImg",row.logoUrl)
          id=row.id
          console.log(id)
          
        }
        return(
          <Space>
            <Button onClick={editInfo} type="primary" shape="round" icon={<FormOutlined />}>
              修改
            </Button>
            <Button onClick={deleteInfo} type="primary" danger shape="round" icon={<DeleteOutlined />}>
              删除
            </Button>
          </Space>
        )
      }
    },
  ];

  // 上传图片LOGO相关
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };
  
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };
  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  const onChange: PaginationProps["onChange"] = (pageNumber) => {
    // console.log('Page: ', pageNumber);
    currentPage = pageNumber
    dispatch(getTrademarkListSync(pageNumber, pageSize));
  };
  const onShowSizeChange =(current:number,size:number)=>{
    currentPage=current
    pageSize=size
    // console.log(current,size)
    dispatch(getTrademarkListSync(currentPage, pageSize));
  }

  const arr = [2, 5, 10];
  // 发送请求
  useEffect(() => {
    // dispatch(getHospitalSetSync(1, pageSize));
    dispatch(getTrademarkListSync(currentPage, pageSize));
  }, []);

  return (
    <Card style={{ padding: 0 }}>
      <Button type="primary" onClick={showModal}>
        添加
      </Button>
      <Divider />
      <Table
        rowKey="id"
        columns={columns}
        dataSource={data}
        pagination={false}
      />
      <Pagination
        defaultPageSize={5}
        total={trademarkList.total}
        pageSizeOptions={arr}
        onChange={onChange}
        onShowSizeChange={onShowSizeChange}
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `总 ${trademarkList.total} 条`}
      />
      <Modal
        footer={[]}
        title="Basic Modal"
        visible={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} {...layout} name="nest-messages" onFinish={onFinish}>
          <Form.Item name="logoName" labelAlign={"left"} label="商品名字">
            <Input />
          </Form.Item>
          <Form.Item
            valuePropName="fileList"
            getValueFromEvent={normFile}
            name="logoImg"
            labelAlign={"left"}
            label="品牌LOGO"
          >
            <Upload
              // name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://gmall-h5-api.atguigu.cn/admin/product/fileUpload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
          <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
            <Button  type="primary" htmlType="submit">
              提交
            </Button>
            <Button onClick={handleCancel}>取消</Button>
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default Index;
